/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2025-05-19 19:42:46
 * @LastEditTime: 2025-05-20 21:37:11
 * @FilePath: /monitor_belt/src/views/home/components/video-stream/index.tsx
 */

import { startStream, stopStream } from "@/api/stream";
import { useEffect, useRef } from "react";
import flvjs from 'flv.js';

const VideoStream = (props: { info: any }) => {
  let { info } = props;
  let videoRef = useRef(null);

  useEffect(() => {
    if (info.id) {
      start(info.id);
      return () => {
        stop(info.id);
      };
    }
  }, [info]);
  //开始拉流
  const start = async (id) => {
    try {
      let res = await startStream(id);
      let videoUrl = res.data;
      if (flvjs.isSupported()) {
        let videoElement = document.getElementById(`video_${info.id}`)
        videoRef.current = flvjs.createPlayer({
          type: 'flv',
          url: videoUrl,
          isLive: true, // 是否为直播流
        });
        videoRef.current.attachMediaElement(videoElement);
        videoRef.current.load();
      }
      console.log(res);
    } finally {
    }
  };
  //停止
  const stop = async (id) => {
    try {
      await stopStream(id);
    } finally {
    }
  };

  return (
    <>
      <video style={{ width: "100%" }} autoPlay muted id={`video_${info.id}`} ref={videoRef}></video>
    </>
  );
};

export default VideoStream;
